<script setup lang="ts">
import { apiAddressDefault } from "@/apis/address";
import { apiComfirmOrder, wxPayMiniAppPay } from "@/apis/order";
import { apiProductDetails } from "@/apis/product";
import { router, shortenString, toast } from "@/utils/tools";
import { onShow } from "@dcloudio/uni-app";
import { onLoad } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();
import { ref, reactive, computed } from "vue";
const payDisabled = ref(false);
const orderId = ref(0);
const myDefaultAddress: any = reactive({});
const isDefaultAddress = ref(false);
const productDetail: any = reactive({});
const shoppingId = ref();
const getDetail = async () => {
  let res = await apiProductDetails({ id: orderId.value });
  Object.assign(productDetail, res.data);
  productDetail.images = productDetail?.images?.split(",");
  productDetail.describes = shortenString(productDetail.describes, 20);
  productDetail.dict = JSON.parse(productDetail.dict);
};
// 查询默认地址
const getAddressDefault = async () => {
  let res = await apiAddressDefault({ state: 1 });
  if (res.data.length > 0) {
    isDefaultAddress.value = true;
  }
  Object.assign(myDefaultAddress, res?.data?.[0] || {});
};
const comfirmOrder = async () => {
  if (JSON.stringify(myDefaultAddress) === '{}') {
    toast("请添加默认地址！");
    return
  }
  if (productDetail.appUserId === userStore.userInfo.id) {
    toast("自己的商品无法购买！");
    return;
  }

  let data = {
    commodityId: productDetail.id, //商品ID
    commodityName: productDetail.title, //商品的标题名称
    actualPayment: productDetail.currentPrice, //支付价格
    userAddressId: myDefaultAddress.id, //发货地址ID
    type: 2, //消费类型  0-开会员  1-开商铺  2-购买商品  3-藏品认证  4-评价费用
    activitiesId: null, //评选活动Id
    appCommodityList: null, // 4评价活动的时候传
    collectionCertificationList: null, // 3藏品认证的时候传
  };
  // let res = await apiComfirmOrder(data);
  // if (res.code == 200) {
  //   shoppingId.value = res.data.shopingId;
  //   wxPayMiniAppPayFn();
  // }
  await wxPayMiniAppPayFn(data);
};

const wxPayMiniAppPayFn = async (data: any) => {
  let res = await wxPayMiniAppPay(data);
  if (res.code == 200) {
    // let dataObj = JSON.parse(res.data);
    let dataObj = res.data;
    wx.openEmbeddedMiniProgram({
      appId: dataObj.appId,
      path: dataObj.path,
      envVersion: 'release',//正常跳转路径
      success(res) {
        uni.setStorageSync('isPaySuccess',true)
      }
    })
    return
    const { appId, nonceStr, paySign, signType, timeStamp } = dataObj;
    const packages = dataObj.package;
    uni.requestPayment({
      provider: "wxpay",
      appId: appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
      nonceStr: nonceStr, // 随机字符串
      package: packages, // 固定值
      signType: signType,
      timeStamp: timeStamp, // 时间戳（单位：秒）
      paySign: paySign, // 签名，这里用的 MD5/RSA 签名
      success(res) {
        toast("支付成功！");
        payDisabled.value = true;
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/index/index",
          });
        }, 1000);
      },
      fail(e) {
        payDisabled.value = false;
        if (e.errMsg === "requestPayment:fail cancel") {
          toast("支付取消");
        } else {
          toast("支付失败");
        }
      },
    });
  }
};
const isImg = (url = "") => {
  if (
    url.indexOf(".png") > -1 ||
    url.indexOf(".jpg") > -1 ||
    url.indexOf(".jpeg") > -1 ||
    url.indexOf(".webp") > -1
  ) {
    return true;
  }
  return false;
};
const filterPlayCount = computed(() => {
  return (str) => {
    if (isImg(str)) {
      return str;
    }
    return str + "?x-oss-process=video/snapshot,t_0,f_jpg";
  };
});
onShow(() => {
  uni.$on("addressInfo", (res: any) => {
    Object.assign(myDefaultAddress, res);
    isDefaultAddress.value = true;
  });
  getAddressDefault();
  getDetail();
});
onLoad((options: any) => {
  orderId.value = options.orderId;
  getAddressDefault();
});
</script>
<template>
  <view class="body-box">
    <view class="row-box location-box" @click="router('/pagesMy/address/choose')" v-if="isDefaultAddress">
      <view class="top-box flex flex-align-center">
        <view class="default">默认</view>
        <view>{{ myDefaultAddress?.area }}</view>
      </view>
      <view class="center-box flex flex-between">
        <view>{{ myDefaultAddress?.address }}</view>
        <view>
          <image src="@/static/images/return_grey.png" />
        </view>
      </view>
      <view class="bto-box">收货人：{{ myDefaultAddress?.recipient }}（{{
        myDefaultAddress?.phone
        }}）</view>
    </view>
    <view class="row-box location-box flex-align-center" v-else @click="router('/pagesMy/address/choose')">
      <view class="flex flex-between">
        <view>添加地址</view>
        <view>
          <image class="to" src="@/static/images/return_grey.png" />
        </view>
      </view>
    </view>
    <!-- 优惠券 -->
    <!-- <view
      class="row-box location-box"
    >
      <view class="top-box flex flex-align-center">
      </view>
      <view class="center-box flex flex-between">
        <view>优惠券</view>
        <view class="conpon">
          <view>-¥0.00</view>
          <image src="@/static/images/return_grey.png" />
        </view>
      </view>
    </view> -->
    <!-- end -->
    <view class="row-box shop-box">
      <view class="shop-name flex flex-align-center">
        <image src="@/static/images/shop-2.png" class="img" />
        {{ productDetail.shopName }}
      </view>
      <view class="commodity-box">
        <view class="commodity-info flex flex-align-center">
          <view class="commodity-img">
            <image :src="filterPlayCount(productDetail.images?.[0])" class="img" />
          </view>
          <view class="info-text">
            <view class="title">{{ productDetail.describes }}</view>
            <view class="tag-box">平台认证</view>
            <view class="price-box flex justify-between">
              <view class="price-text flex flex-align-center">
                <text>￥</text>
                <text>{{ productDetail.currentPrice }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="box flex justify-between" v-for="item in productDetail.dict" :key="item.id">
          <view>{{ item.fieldName }}</view>
          <view>{{ item.name }}</view>
        </view>
        <!-- <view class="box flex justify-between">
                    <view>品牌</view>
                    <view>{{ productDetail.brand }}</view>
                </view>
                <view class="box flex justify-between">
                    <view>成色</view>
                    <view>{{ productDetail.fineness }}</view>
                </view> -->
        <view class="box flex justify-between">
          <view>配送</view>
          <text v-if="productDetail.delivery == 0">包邮</text>
          <text v-if="productDetail.delivery == 1">不包邮</text>
          <text v-if="productDetail.delivery == 2">自取</text>
        </view>
      </view>
    </view>
    <view class="button-box flex flex-between">
      <view class="sum-box">
        <text>共计</text>
        <text class="unit">￥</text>
        <text class="red">{{ productDetail.currentPrice }}</text>
      </view>
      <view class="payment-btn" @click="comfirmOrder">
        <button :disabled="payDisabled">立即付款</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.body-box {
  padding: 12px 15px;
  box-sizing: border-box;
}

.to {
  width: 40rpx;
  height: 40rpx;
}

.location-box {
  margin-bottom: 12px;
  color: rgba(16, 16, 16, 1);
  font-size: 14px;

  .top-box {
    margin-bottom: 10px;

    .default {
      margin-right: 10px;
      padding: 2px 6px;
      border-radius: 2px;
      background: linear-gradient(89.54deg,
          rgba(255, 131, 2, 1) 0.69%,
          rgba(254, 55, 27, 1) 99.31%);
      color: rgba(255, 255, 255, 1);
      font-size: 12px;
      border: 0px solid rgba(187, 187, 187, 1);
    }
  }

  .center-box {
    margin-bottom: 10px;

    image {
      width: 20px;
      height: 20px;
    }
  }
}

.shop-box {
  .shop-name {
    margin-bottom: 15px;
    color: rgba(16, 16, 16, 1);
    font-size: 14px;

    .img {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }

  .commodity-box {
    .commodity-info {
      margin-bottom: 5px;

      .commodity-img {
        margin-right: 10px;

        .img {
          width: 86px;
          height: 86px;
          border-radius: 8px;
        }
      }

      .info-text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 86px;

        .title {
          color: rgba(16, 16, 16, 1);
          font-size: 14px;
        }

        .tag-box {
          width: 60px;
          height: 20px;
          border-radius: 3px;
          color: rgba(50, 140, 254, 1);
          font-size: 12px;
          text-align: center;
          border: 1px solid rgba(50, 140, 254, 1);
        }

        .price-box {
          .price-text {
            text {
              color: rgba(243, 96, 78, 1);
              font-size: 18px;

              &:first-child {
                margin-right: 5px;
                font-size: 12px;
              }
            }
          }

          .original-price {
            margin-left: 10rpx;
            color: rgba(206, 206, 206, 1);
            font-size: 12px;
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }

  .box {
    padding: 12.5px 0;
    border-bottom: 1px solid rgba(239, 239, 239, 1);
    color: rgba(16, 16, 16, 1);
    font-size: 14px;

    &:last-child {
      padding-bottom: 0;
      border-bottom: none;
    }
  }
}

.button-box {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  padding: 10px 15px 20px;
  box-sizing: border-box;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0rpx -4rpx 4rpx 0rpx rgba(0, 0, 0, 0.1);
  border: 0rpx solid rgba(187, 187, 187, 1);

  .sum-box {
    text {
      color: rgba(154, 154, 154, 1);
      font-size: 14px;
    }

    .unit {
      margin-left: 5px;
      color: rgba(243, 96, 78, 1);
      font-size: 16px;
    }

    .red {
      color: rgba(243, 96, 78, 1);
      font-size: 20px;
    }
  }

  .payment-btn {
    button {
      width: 150px;
      height: 40px;
      line-height: 20px;
      border-radius: 20px;
      background: linear-gradient(0deg,
          rgba(191, 1, 3, 1) 0%,
          rgba(255, 84, 2, 1) 99.2%);
      color: rgba(255, 255, 255, 1);
      font-size: 14px;
      text-align: center;
      border: 0px solid rgba(187, 187, 187, 1);
    }
  }
}

.conpon {
  display: flex;
}
</style>
